<template>
	<view class="container">
		<!-- 水印 -->
		<water-mask></water-mask>
		<!-- 背景颜色 -->
		<view style="background-color: #FFFFFF;">
			<view class="flex-content">
				<!-- 分类列表 -->
				<view class="end-title">
					<view v-for="(item,index) in categoryList" :key="index" :class="{btna:countNum == index}"
						@tap="changeMenu(index)">
						{{item.name}}
					</view>
				</view>
				<view class="end-cont">

					<view class="goods">

						<view v-if="(categoryName=='全部'?true:item.productCategoryName==categoryName)"
							v-for="(item,index) in goodsListNew" :key="index">
							<goods-card @child-event2="calculation" @child-event-numberchange="parentEventHandler"
								:price="item.price" @child-event="dialogToggle" :id="item.productId"
								:oldprice="item.originalPrice" :name="item.productName"
								:num="item.buynum"></goods-card>
						</view>


					</view>

				</view>
			</view>

		</view>
		<!-- buy -->
		<view>
			<!-- 确认购买数量 -->
			<uni-popup ref="buyDialog" type="dialog">
				<uni-popup-dialog :type="msgType" cancelText="取消" confirmText="确认" title="选择商品数量"
					@confirm="dialogConfirm" @close="dialogClose">
					<uni-number-box v-model="buyNum" />
				</uni-popup-dialog>
			</uni-popup>
		</view>
		<view>
			<!-- 提示信息弹窗 -->
			<uni-popup ref="message" type="message">
				<uni-popup-message :type="msgType" :message="messageText" :duration="2000"></uni-popup-message>
			</uni-popup>
		</view>
		<!-- price -->
		<view
			style="display: flex;flex-direction: row; justify-content: flex-end; align-items: center; background-color: #FFFFFF; padding-right: 30rpx; position: absolute;bottom: 0px;left: 0px;right: 0px;height: 13vh;">
			<view style="padding: 30rpx;">总计：¥{{totalAmount}}</view>
			<view
			v-if="!loadingButton"
			@click="submitBag"
				style="background-color:  rgba(0, 122, 255, 1);border-radius: 30px; padding: 20rpx 40rpx 20rpx 40rpx;color: #FFFFFF;">
				提交订单</view>
		</view>
	</view>
</template>
<script>

	import {
		getCategoryList,
		getBatchListAll
	} from '@/api/system/category.js';

	import {
		listOrder,
		getOrderProductList,
		updateOrderProducts,
		addOrderProducts
	} from '@/api/system/order.js';

	export default {

		onLoad(e) {

			this.qurry.batchId = Number(e.piID)
			// 初始化订单实体(用以第一次提交)
			this.queryOrder.omsOrder.userId = getApp().globalData.userInfo.userId
			this.queryOrder.omsOrder.batchId = e.piID
			this.queryOrder.omsOrder.memberUsername = getApp().globalData.userInfo.nickName
			this.queryOrder.omsOrder.deptId = getApp().globalData.userInfo.dept.deptId
			this.queryOrder.omsOrder.deptName = getApp().globalData.userInfo.dept.deptName
			// 初始化订单查询参数
			this.orderParams.batchId = Number(e.piID);
			this.orderParams.userId = getApp().globalData.userInfo.userId;
			getBatchListAll(this.qurry).then(resq => {


				const listHandle = []
				const goodlistHandle = []
				listHandle[0] = {
					name: "全部"
				}
				resq.data[0].pmsProducts.forEach(item => {
					//为每个商品添加购买数量字段
					item.buynum = 0
					goodlistHandle.push(item)
					// 判断数组中是否存在该类别,是否需要创建类别
					const index = listHandle.findIndex(listItem => item.productCategoryName === listItem
						.name);
					if (index < 0) {
						listHandle.push({
							name: item.productCategoryName,
						})
					}
				})
				// 初始化类别
				this.goodsListNew = goodlistHandle
				this.categoryList = listHandle;
	
				this.loadOrder();
			})
			

		},

		data() {
			return {
				//初始查询参数
				qurry: {
					batchId: 0,
				},
				//订单查询参数
				orderParams: {
					batchId: null,
					userId: null,
				},
				categoryName: "全部",
				goodsListNew: [],
				//订单对象,用以加载查询到的订单详情或者提交订单
				queryOrder: {
					omsOrder: {
						orderId: null,
						orderSn: null,
						batchId: null,
						userId: null,
						memberUsername: null,
						totalAmount: null,
						purchasePrice: null,
						status: null,
						autoConfirmDay: null,
						deleteStatus: null,
						receiveTime: null
					},
					orderProductList: []
				},
				// 总商品清单
				baseList: [],
				orderList: '',
				// 购买商品相关
				buyNum: 1,
				chooseId: "",
				messageText: "提示框",

				dialogVisible: false,
				loadingButton:false,
				bagList: [],
				pattern: {
					color: '#7A7E83',
					backgroundColor: '#fff',
					selectedColor: '#007AFF',
					buttonColor: '#007AFF',
					iconColor: '#fff',
					icon: 'cart',
				},
				btnnum: 0,
				categoryList: '',
				items: ["精选推荐", "华为手机", "荣耀手机", "笔记本", "平板电脑", "智能穿戴"],
				countNum: "0",
				search: "",
				goodsList: {},
				msgType: "info",
				totalAmount: 0,

			};
		},
		onShow() {
			// this.goodsList = this.data[0]
		},
		methods: {
			//计算总价
			calculation(e,id) {

				
				let total = 0;
			let goodindex = this.goodsListNew.findIndex(item => {return item
				.productId == id})
				
				if(goodindex>=0){
					this.goodsListNew[goodindex].buynum=e
				}
				
				const index = this.queryOrder.orderProductList.findIndex(item => item
					.productId == id);
					if(index>=0){this.queryOrder.orderProductList[index].productNumber=e}

				this.goodsListNew.forEach(e => {
				
					total += e.price * e.buynum;
				})
				this.totalAmount = total;
			},
			//加载订单
			loadOrder() {

				this.loadingButton = true;
				getOrderProductList(this.orderParams).then(res => {
					//将查询到的订单赋值给订单实体(如果存在)
			
					if (res.data.length > 0) {
						this.queryOrder = res.data[0]
						//根据订单实体初始化商品数量
						if (res.data[0].orderProductList.length > 0) {
							res.data[0].orderProductList.forEach(item => {

								const index = this.goodsListNew.findIndex(itemGoodList => itemGoodList
									.productId === item.productId);

								this.goodsListNew[index].buynum = item.productNumber
							})
						}
					}
				
					this.calculation()
					this.loadingButton = false

				}).catch(()=>{
					this.loadingButton = false
				})
			},
			// buydialog相关
			dialogToggle(e) {
		
				this.chooseId = e,

					this.$refs.buyDialog.open()
			},
			//将商品添加入订单实体
			dialogConfirm() {
				//获取当前商品的index
				const index = this.goodsListNew.findIndex(item => item.productId == this.chooseId);
				// 判断数组中是否包含某个元素
				const contains = this.queryOrder.orderProductList.findIndex(item => item.productId == this
					.chooseId)
				if (contains != -1) {
					if(this.buyNum==0){
						this.queryOrder.orderProductList.splice(contains,1);
					}
					else{
						this.queryOrder.orderProductList[contains].pmsProduct.productNumber += this.buyNum
						
					}
				} else {

					const goodsHandle = {
						batchId: this.queryOrder.omsOrder.batchId,
						orderId: this.queryOrder.omsOrder.orderId,
						productId: this.chooseId,
						productNumber: this.buyNum,
						pmsProduct: this.goodsListNew[index]
					}

					this.queryOrder.orderProductList.push(goodsHandle)
				}
				if(this.buyNum==0){
					
				}
				else{
					this.goodsListNew[index].buynum=this.buyNum
				}
			
				this.calculation()
				this.messageText = `已将 ${this.buyNum}件商品加入订单，提交订单后生效`
				this.$refs.message.open()
				this.buyNum = 1
				

			},
			dialogClose() {

				this.buyNum = 1
			},
			submitBag() {		
				this.queryOrder.omsOrder.totalAmount = this.totalAmount
                       this.loadingButton=true;
				updateOrderProducts(this.queryOrder).then((res) => {
					this.messageText = `已将采买清单更新至当前批次订单中，可在我的订单中查看`;
					this.$refs.message.open();
					this.loadOrder();
					this.loadingButton = false;
				}).
				catch(()=>{
					this.loadingButton =false;
				})

			},
			//监听子组件商品数量是否减少到了0
			parentEventHandler(e) {
				const id = e
				const index = this.queryOrder.orderProductList.findIndex(queryitem => e ===
					queryitem.productId)
				this.queryOrder.orderProductList.splice(index, 1)
				this.calculation()

			},

			inputChange(e) {
				this.calculation();
			},
	
	
			changeMenu(e) {
				// this.calculation();
				this.countNum = e
				this.btnnum = e
				this.categoryName = this.categoryList[e].name
				// this.goodsList = this.categoryList[e].list //这里data是获取到的右侧商品数据


			},
			scroll() {},
			getSearch() {}
		}
	}
</script>








<style scoped lang="scss">
	.bagSubmit {
		position: absolute;
		right: 1rem;
		bottom: 1rem;
		background-color: rgba(0, 122, 255, 1);
		padding: 0.5rem;
		color: #fff;

		box-shadow: 4px 4px 2px #888888;
		border-radius: 0.2rem;
	}

	.bagTotal {
		position: absolute;
		right: -3rem;
		width: 5rem;
		height: 5rem;
		bottom: 3rem;
		color: #000000;
		background-color: rgba(255, 255, 255, 1.0);
		padding: 0.5rem;
		display: flex;
		flex-direction: column;
		border-radius: 0.2rem;
	}

	.popup-content {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.container {
		background-color: #FFFFFF;
		display: flex;
		flex-direction: row;
		height: 100%;
	}

	.main {
		position: fixed;
		display: flex;
		overflow: hidden;
		height: 100%;
	}

	.search-bar {
		width: 100%;
		position: fixed;
		top: 0;
		left: 0;
		color: #777;
		background: #fff;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.07);
		z-index: 3;
		padding: 20rpx 0;

		.arrow {
			width: 20rpx;
			height: 20rpx;
			border-bottom: 2rpx solid #777;
			border-left: 2rpx solid #777;
			transform: rotate(45deg);
			position: absolute;
			left: 30rpx;
			top: 41rpx;
		}

		.search-box {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 60rpx;
			background: #f7f7f7;
			z-index: 999;
			width: 92%;
			border-radius: 50rpx;
			text-align: center;
			margin: auto;

			.search-img {
				width: 32rpx;
				height: 32rpx;
				margin-right: 10rpx;
			}
		}

		.search-hint {
			font-size: 28rpx;
			position: absolute;
			right: 30rpx;
			top: 32rpx;
		}
	}

	.sear-input {
		font-size: 28rpx;
	}

	.navBar {
		padding: 5rpx 32rpx 6rpx 28rpx;
		height: 80rpx;
		display: flex;
		align-items: center;

		&-search {
			margin: 0 auto;
			width: 690rpx;
			height: 58rpx;
			background-color: #F8F9FA;
			border-radius: 30rpx;
			padding-left: 16rpx;
			// margin-right: 32rpx;
			display: flex;
			justify-content: flex-start;
			align-items: center;

			input {
				margin-left: 20rpx;
			}
		}
	}

	.flex-content {
		display: flex;
	}

	.end-title {
		display: flex;
		flex-direction: column;
		width: 180rpx;
		background-color: #F3F5F7;
		height: 80vh;
		overflow-y: auto;

		view {
			height: 100rpx;
			line-height: 100rpx;
			text-align: center;
			font-size: 26rpx;
			font-weight: bold;
			color: #4E5152;
			border-bottom: 1rpx solid #ECEDEE;
			border-left: 8rpx solid #F3F5F7;
		}

		.btna {
			color: #FF6C5C;
			background-color: #FFFFFF;
			border-left: 8rpx solid #FF6C5C;
		}
	}

	/* .end-title view{flex-grow:1;text-align:center;} */
	.end-cont {
		// width: 550rpx;
		padding-right: 50rpx;


		.title {
			font-size: 30rpx;
			font-weight: bold;
			text-align: center;
			color: #4E5152;
		}

		.goods {
			// font-size: 10rpx;
			width: 100%;
			display: flex;
			flex-direction: column;
			// justify-content: space-around;
			// flex-wrap: wrap;
			height: 80vh;
			overflow-y: auto;

		}

		image {
			margin: 20rpx 0 60rpx 20rpx;
		}
	}

	.dis {
		display: block;
	}
</style>